const {
    Builder,
    By,
    Key,
    until,
} = require('selenium-webdriver');
// 设置无头浏览器
let chrome = require('selenium-webdriver/chrome');
const express = require('express')
const app = express()
const fs = require('fs')
// 公开静态文件
app.use('/node_modules', express.static('./node_modules'))
app.engine('html', require('express-art-template'));

app.get('/', async (req, res) => {
    res.render("index.html")
})

// 获取基金信息的方法
app.get('/getFundInfo', async (req, res) => {
    await example(data => {
        res.status(200).json({
            code:0,
            data:data
        })
    })
})

// 启动端口
app.listen(3000, () => {
    console.log("127.0.0.1:3000");
})

// 声明一个自执行方法
async function example(callback) {
    // 实例化 Chrome 浏览器
    let driver = new Builder()
        .forBrowser('chrome')
        .setChromeOptions(new chrome.Options().headless())
        .build();
    try {
        let infoList = [];
        let funkList = ['003095', '161028']
        for (let index = 0; index < funkList.length; index++) {
            const code = funkList[index];
            let fundInfo = {}
            // 打开基金持仓页面
            await driver.get(`http://fundf10.eastmoney.com/ccmx_${code}.html`);
            // 获取基金名称
            let title = await driver.findElement(By.css('.col-left>h4.title')).getText()
            // 获取是否涨跌
            let fundgz = await driver.findElement(By.id('fundgz_icon')).getAttribute('class')
            fundgz = fundgz.replace('icon  ', '')
            fundgz = fundgz === 'icon-up' ? '涨' : '跌'
            // 获取涨跌幅
            let fund_gszf = await driver.findElement(By.id('fund_gszf')).getText()
            // 获得持仓的表格
            let cctable = await driver.findElements(By.css("#cctable>.box>.boxitem>.w782 tbody tr"))
            fundInfo['title'] = title;
            fundInfo['fundgz'] = fundgz;
            fundInfo['fund_gszf'] = fund_gszf;
            fundInfo['ccSock'] = []
            for (let i = 0; i < cctable.length; i++) {
                const item = cctable[i];
                // 获取股票名称
                let name = await item.findElement(By.css('td:nth-child(3)>a')).getText()
                // 获取股票价格
                let money = await item.findElement(By.css('td:nth-child(4)>span')).getText()
                // 获取股票涨跌
                let zf = await item.findElement(By.css('td:nth-child(5)>span')).getText()
                fundInfo['ccSock'].push({
                    'name': name,
                    'money': money,
                    'zf': zf
                });
            }
            infoList.push(fundInfo)
        }
        callback(infoList)
    } catch (error) {
        console.log(error);
    }
};